package com.example.goodpet.activity.Fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.example.goodpet.R;
import com.example.goodpet.base.BaseFragment;
import com.example.goodpet.base.BaseFragmentForView;
import com.example.goodpet.bean.ResponseBody;
import com.example.goodpet.bean.UserPetInfo;
import com.example.goodpet.common.EndlessRecyclerOnScrollListener;
import com.example.goodpet.common.LoadMoreWrapper;
import com.example.goodpet.common.LoadingPage;
import com.example.goodpet.home.fragment.HomeFragment;
import com.example.goodpet.home.homeRecommend.adapter.RecommendRecycleViewAdapter;
import com.example.goodpet.service.HomeService;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.TimeSeed;
import com.example.goodpet.utils.UIUtils;
import com.github.gzuliyujiang.dialog.DialogColor;
import com.github.gzuliyujiang.dialog.DialogConfig;
import com.github.gzuliyujiang.dialog.DialogStyle;
import com.github.gzuliyujiang.wheelpicker.AddressPicker;
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode;
import com.github.gzuliyujiang.wheelpicker.contract.OnAddressPickedListener;
import com.github.gzuliyujiang.wheelpicker.entity.CityEntity;
import com.github.gzuliyujiang.wheelpicker.entity.CountyEntity;
import com.github.gzuliyujiang.wheelpicker.entity.ProvinceEntity;

import java.util.LinkedList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


public class SearchResultOfPetFragment extends BaseFragmentForView {
    private static final String TAG = HomeFragment.class.getSimpleName();

    private TextView tv_screening_location;
    private RecyclerView rv_search_result_pet;

    private Retrofit retrofit;
    private HomeService homeService;

    private List<UserPetInfo> userPetInfos;

//    用来获取布局
    private LayoutInflater mLayoutInflater;
    private List<DelegateAdapter.Adapter> subAdapters = new LinkedList();
//    VLayout
    private VirtualLayoutManager layoutManager;

    private String location="地区";
    private String searchContent;
    private long seed= TimeSeed.Get();

    @Override
    protected void initView(View inflate) {
        super.initView(inflate);
        tv_screening_location=inflate.findViewById(R.id.tv_screening_location);
        rv_search_result_pet=inflate.findViewById(R.id.rv_search_result_pet);

        if(MyApplication.location == ""){
//            UIUtils.toast("定位失败",false);

        }else{
            //定位成功，location修改成相应的定位，tv_screening_location外显文本也发生相应改变
            location=MyApplication.location;
        }
        tv_screening_location.setText(location);
        location=tv_screening_location.getText().toString();
    }


    @Override
    public void initData() {
        searchContent=getArguments().getString("searchContent");
        retrofit= RetrofitSingleton.getRetrofitConstance();
        homeService=retrofit.create(HomeService.class);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_search_result_of_pet;
    }


    private void initVLayoutRvPet() {
        //1.设置总布局管理器
        layoutManager = new VirtualLayoutManager(mContext);
        rv_search_result_pet.setLayoutManager(layoutManager);
        //2.设置回收池大小（相同类型的View可以复用，防止多次创建ItemView）
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 10);
        rv_search_result_pet.setRecycledViewPool(viewPool);
        //3.逐个设置子模块适配器
        subAdapters.clear();
        addPetAdapter();

        //4.设置总适配器
        DelegateAdapter mainAdapter = new DelegateAdapter(layoutManager, true);
        mainAdapter.setAdapters(subAdapters);
        rv_search_result_pet.setAdapter(mainAdapter);
    }

    private void addPetAdapter() {
        GridLayoutHelper layoutHelper = new GridLayoutHelper(2);
        RecommendRecycleViewAdapter adapter = new RecommendRecycleViewAdapter(mContext, userPetInfos);
        LoadMoreWrapper loadMoreWrapper = new LoadMoreWrapper(adapter){
            @Override
            public LayoutHelper onCreateLayoutHelper() {
                return layoutHelper;
            }
        };
        subAdapters.add(loadMoreWrapper);

        rv_search_result_pet.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING);
                homeService.selectUserPetInfoBySearch(seed,searchContent ,location , ++loadMoreWrapper.page)
                        .enqueue(new Callback<ResponseBody<List<UserPetInfo>>>() {
                            @Override
                            public void onResponse(Call<ResponseBody<List<UserPetInfo>>> call, Response<ResponseBody<List<UserPetInfo>>> response) {
                                ResponseBody<List<UserPetInfo>> body1 = response.body();
                                if (body1.getCode()==200){
                                    List<UserPetInfo> data1 = body1.getData();
                                    userPetInfos.addAll(data1);
                                    loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_COMPLETE);
                                }else if (body1.getCode()==404){
                                    loadMoreWrapper.setLoadState(loadMoreWrapper.LOADING_END);
                                }

                            }
                            @Override
                            public void onFailure(Call<ResponseBody<List<UserPetInfo>>> call, Throwable t) {
                                UIUtils.toast("连接服务器失败",false);
                            }
                        });
            }
        });
    }

    public void initListener() {
        super.initListener();
        tv_screening_location.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                DialogConfig.setDialogStyle(DialogStyle.Three);
                DialogConfig.setDialogColor(new DialogColor()
                        .cancelTextColor(0xFF999999)
                        .okTextColor(0xFF0099CC));

                AddressPicker picker = new AddressPicker(getActivity());
                picker.setAddressMode(AddressMode.PROVINCE_CITY);

                picker.setOnAddressPickedListener(new OnAddressPickedListener() {
                    @Override
                    public void onAddressPicked(ProvinceEntity province, CityEntity city, CountyEntity county) {
                        /**
                         * 监测到地区改变，外显按钮文本进行相应的改变后，根据用户选择重新初始化对应的宠物信息
                         */
                        if(null!=city){
                            tv_screening_location.setText(city.getName());
                        }else{
                            tv_screening_location.setText(province.getName());
                        }
                        location=tv_screening_location.getText().toString();
//                        UIUtils.toast(location,false);
                        LoadPage();
                    }
                });
                picker.show();
            }
        });

    }

    @Override
    protected void LoadPage() {
        loadingPage.setStateCurrent(LoadingPage.STATE_loading);
        homeService.selectUserPetInfoBySearch(seed,searchContent,location,1)
                .enqueue(new Callback<ResponseBody<List<UserPetInfo>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<UserPetInfo>>> call, Response<ResponseBody<List<UserPetInfo>>> response) {
                        ResponseBody<List<UserPetInfo>> body = response.body();
                        Log.e(TAG, "onResponse: "+body.getCode() );
                        if(body.getCode()==200){
                            loadingPage.setStateCurrent(LoadingPage.STATE_SUCCESS);
                            userPetInfos = body.getData();
                        }else{
                            userPetInfos = null;
                            //UIUtils.toast("未获取到响应数据",false);
                            loadingPage.setStateCurrent(LoadingPage.STATE_EMPTY);
                        }
                        //获取数据成功后初始化显示宠物信息的recyclerview
                        initVLayoutRvPet();
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<UserPetInfo>>> call, Throwable t) {
                        Log.e(TAG, "onFailure: "+t.getMessage() );
                        //UIUtils.toast("通信失败",false);
                        loadingPage.setStateCurrent(LoadingPage.STATE_ERROR);
                    }
                });
    }


}